﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Mvc;
using System.ComponentModel;
using EIIS.Infrastructure.Service.System.Authority;
using EIIS.Infrastructure.Model.System.Authority;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;

namespace EIIS.Presentation.Controllers.System.Authority
{
    [Description("菜单管理")]
    public class MenuController : BaseController
    {
        public IActionPermissionManager ActionPermissionManager { get; set; }
        public IMenuManager MenuManager { get; set; }

        [Description("菜单管理页面")]
        [ViewPage]
        public ActionResult Index()
        {
            AddMenuRoot();
            return View();
        }

        public ActionResult LoadAll()
        {
            List<MenuNode> list = MenuManager.LoadAll().OrderBy(m => m.Index).ToList() ;
            List<MenuGrid> gridList = ConvertToGrid(list);

            return this.JsonFormat(new GridData { total = gridList.Count, rows = gridList });
        }

        public ActionResult LoadAllPageByAssembly(int page, int rows)
        {
            string strKeyword = Request["q"];
            long total = 0;
            IList<ActionPermission> ilist = ActionPermissionManager.GetAllPageActionByAssembly(out total, page, rows, "", "", strKeyword);
            return this.JsonFormat(new GridData { total = total, rows = ilist.ToList() });
        }

        [Description("新增菜单")]
        [Function(ButtonID = "btnAdd")]
        public ActionResult Add(string id)
        {
            MenuNode parent = MenuManager.Get(id);
            MenuNode entity = new MenuNode
            {
                ParentId = parent.Id,
                Level = parent.Level + 1
            };
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("修改菜单")]
        [Function(ButtonID = "btnUpdate")]
        public ActionResult Edit(string id)
        {
            MenuNode entity = this.MenuManager.Get(id);
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("删除菜单")]
        [Function(ButtonID = "btnDelete")]
        public ActionResult Delete(IList<string> idList)
        {
            MessageInfo msg = new MessageInfo();
            foreach (string strId in idList)
            {
                if (MenuManager.HasChild(strId))
                {
                    msg.IsSuccess = false;
                    msg.Message = "删除失败，您所删除的数据中有子信息，请重新选择";
                    return Json(msg);
                }
            }
            msg.IsSuccess = true;
            msg.Message = "删除成功";
            MenuManager.Delete(idList.Cast<object>().ToList());
            return Json(msg);
        }

        [Description("保存菜单")]
        [HttpPost]
        public ActionResult Save(MenuNode entity)
        {
            MessageInfo msg = new MessageInfo();
            if (string.IsNullOrEmpty(entity.Id))//新增
            {
                if (MenuManager.IsExistWithName(entity.Name, "-1", ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，已存在该菜单名称的记录";
                    return Json(msg);
                }
                if (MenuManager.IsExistWithTreeCode(entity.Name, "-1", ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，已存在该代码的记录";
                    return Json(msg);
                }
                if (string.IsNullOrEmpty(entity.ControllerName))
                {
                    entity.ActionName = string.Empty;
                    entity.IsPage = false;
                }
                else
                {
                    entity.IsPage = true;
                }
                entity.Id = Guid.NewGuid().ToString();
                entity.Url = MenuNode.GetURL(entity.ControllerName, entity.ActionName);
                MenuManager.Save(entity);
            }
            else
            {
                var model = MenuManager.Get(entity.Id);
                if (MenuManager.IsExistWithName(entity.Name, entity.Id, ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "修改失败，已存在该菜单名称的记录";
                    return Json(msg);
                }
                if (MenuManager.IsExistWithTreeCode(entity.Name, entity.Id, ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "修改失败，已存在该代码的记录";
                    return Json(msg);
                }
                model.Name = entity.Name;
                model.TreeCode = entity.TreeCode;
                model.Index = entity.Index;
                //model.ActionName = entity.ActionName;
                //model.ControllerName = entity.ControllerName;
                model.Description = entity.Description;
                MenuManager.Update(model);
            }
            msg.IsSuccess = true;
            msg.Message = "保存成功";
            return Json(msg, "text/html", JsonRequestBehavior.AllowGet);
        }

        #region 私有方法

        private void AddMenuRoot()
        {
            IList<MenuNode> list = MenuManager.Find("from MenuNode d where d.Level=0");
            if (list.Count == 0)
            {
                MenuNode root = MenuManager.CreateRoot();
                MenuManager.Save(root);
            }
        }

        private MenuGrid ConvertToGrid(MenuNode menuNode)
        {
            MenuGrid grid = new MenuGrid();
            grid.id = menuNode.Id;
            grid.name = menuNode.Name;
            grid.code = menuNode.TreeCode;
            grid._parentId = menuNode.ParentId;
            grid.description = menuNode.Description;
            grid.index = menuNode.Index;
            grid.ispage = menuNode.IsPage;
            grid.lever = menuNode.Level;
            grid.url = MenuNode.GetURL(menuNode.ControllerName, menuNode.ActionName);

            return grid;
        }

        private List<MenuGrid> ConvertToGrid(IList<MenuNode> iList)
        {
            List<MenuGrid> list = new List<MenuGrid>();
            foreach (MenuNode tempc in iList)
            {
                MenuGrid grid = ConvertToGrid(tempc);
                list.Add(grid);
            }
            return list;
        }

        #endregion 
    }
}
